package com.sunmouse.toollib.utils;

import android.graphics.Paint;
import android.graphics.Rect;
import android.text.TextUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Kvin on 2017/1/6.
 */
public class StringUtils {
    public static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public static final String REGEX_NUMBER = "\\d+";
    private static final String WEB_REGEX = "[a-zA-z]+://\\S*";
    @Deprecated
    private static final String MOBIlE_REGEX = "^((13[0-9])|(17[0-9])|(15[^4,\\D])|(18[0-3,5-9]))\\d{8}$";
    private static final String LAST_MOBILE_REGEX = "^((13[0-9])|(15[^4])|(166)|(17[0-8])|(18[0-9])|(19[8-9])|(147,145))\\d{8}$";

    private static final String EMAIL_REGEX = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";

    //Json tools
    private static JSONObject object;

    public static String combineB(String prefix, String suffix) {
        return prefix + "_" + suffix;
    }

    public static String combineM(String prefix, String suffix) {
        return prefix + "_" + suffix;
    }


    /**
     * to percent
     */
    public static String toPercent(float value, int length) {
        String out = String.valueOf(value * 100);
        int index = out.indexOf(".");
        return out.substring(0, index + length + 1) + "%";
    }

    public static String toPercent(float value) {
        return toPercent(value, 2);
    }

    /**
     * check whether a string can be parsed into integer
     */
    public static boolean isNumber(String src) {
        if (src.matches(REGEX_NUMBER)) return true;
        return false;
    }

    /**
     * check whether a string is empty
     */
    public static boolean isEmpty(String src) {
        if (src == null || src.equals("")) return true;
        return false;
    }

    /**
     * parse into time
     */
    public static String parseTime(int sm) {
        sm /= 1000;
        int min = sm / 60;
        int sec = sm % 60;

        return String.format("%02d:%02d", min, sec);
    }

    /**
     * parse  %02d:%02d into millis
     */
    public static int parseTime(String time) {
        String[] st = time.split(":");
        if (st.length < 2) return -1;
        int min = Integer.parseInt(st[0]);
        int sec = Integer.parseInt(st[1]);

        return (min * 60 + sec) * 1000;
    }

    /**
     * parse float
     *
     * @param value
     * @return
     */
    public static float parseFloat(String value) {
        try {
            return Float.parseFloat(value);
        } catch (Exception e) {
            return 0.f;
        }
    }

    public static int parseInt(String value) {
        try {
            return Integer.parseInt(value);
        } catch (Exception e) {
            return 0;
        }
    }


    /**
     * get file type
     */

    public static String getFileName(String input) {
        if (isEmpty(input)) return null;
        return input.substring(input.lastIndexOf("."), input.length());
    }

    /**
     * remove prefix
     */
    public static String removePrefix(String input) {
        return removePrefix(input, ".");
    }

    public static String removePrefix(String input, String symbol) {
        return input.substring(input.indexOf(symbol) + 1, input.length());
    }

    /**
     * remove suffix
     */
    public static String removeSuffix(String input) {
        return removeSuffix(input, ".");
    }

    public static String removeSuffix(String input, String symbol) {
        return input.substring(0, input.lastIndexOf(symbol));
    }


    /**
     * list to string
     *
     * @param list   data resource
     * @param symbol a divide symbol
     */
    public static String intoString(List<String> list, String symbol) {
        String output = "";
        if (ListUtils.isEmpty(list)) return output;
        for (int i = 0; i < list.size(); i++) {
            if (i == list.size() - 1) return output + list.get(i);
            output += list.get(i) + symbol;
        }

        return output;
    }

    /**
     * a string array to string
     *
     * @param src    data resource
     * @param symbol a divide symbol
     */
    public static String intoString(String[] src, String symbol) {
        String output = "";
        if (isEmpty(src)) return output;
        for (int i = 0; i < src.length; i++) {
            if (i == src.length - 1) return output + src[i];
            output += src[i] + symbol;
        }
        return output;
    }

    /**
     * judge whether a string array is empty
     */
    public static boolean isEmpty(String[] srs) {
        if (srs == null || srs.length <= 0) return true;
        return false;
    }

    /**
     * get suffix
     */
    public static String getMediaSuffix(String s) {
        return s.substring(s.lastIndexOf(".") + 1, s.length());
    }

    /**
     * text width
     */
    public static float getTextWidth(String txt, Paint txtPaint) {
        Rect rect = new Rect();
        txtPaint.getTextBounds(txt, 0, txt.length(), rect);
        return rect.width();
    }

    /**
     * text height
     *
     * @return
     */
    public static float getTextHeight(Paint txtPaint) {
        Paint.FontMetrics fontMetrics = txtPaint.getFontMetrics();
        return Math.abs(fontMetrics.top);
    }

    //generate getRequest params
    public static String generateGetParams(HashMap<String, String> params) {
        String str = "?";
        for (Map.Entry<String, String> entry : params.entrySet()) {
            str += entry.getKey() + "=" + entry.getValue() + "&";
        }
        return str.substring(0, str.length() - 1);
    }

    // judge whether a string can be convert to JSONObject by using exception
    public static boolean isJSONObject(String src) {
        //if (src.contains("\\")) src = src.replace("\\", "");
        try {
            object = new JSONObject(src);
        } catch (JSONException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public static String toStringFromStream(InputStream is) {
        if (is == null) {
            throw new NullPointerException("Error: stream is null !");
        }
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String t = "";
        String out = "";
        try {
            while ((t = br.readLine()) != null) {
                out += t;
            }
            is.close();
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return out;
    }

    public static JSONObject getJSONObject() {
        return object;
    }

    //check url
    public static boolean isValidUrl(String url) {
        if (url.matches(WEB_REGEX)) return true;
        return false;
    }

    //check mobile number
    public static boolean isValidNo(String no) {
        if (no.matches(LAST_MOBILE_REGEX)) return true;
        return false;
    }

    //check email
    public static boolean isValidEmail(String email) {
        if (email.matches(EMAIL_REGEX)) return true;
        return false;
    }

    /**
     * get string
     */
    public static String getString(String src) {
        if (isEmpty(src)) return "";
        return src;
    }

    /**
     * convert string to array
     *
     * @param src
     * @param symbol
     * @return
     */
    public static String[] convertToArray(String src, String symbol) {
        if (TextUtils.isEmpty(src)) return null;
        return src.split(symbol);
    }

    public static String[] convertToArray(String src) {
        return convertToArray(src, "-");
    }

    /**
     * to json string
     */
    public static String toJsonString(HashMap<String, String> src) {
        JSONObject obj = new JSONObject();
        try {
            for (Map.Entry<String, String> e : src.entrySet()) {
                obj.put(e.getKey(), e.getValue());
            }
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
        return obj.toString();
    }

    /**
     * to list
     */
    public static List<String> toList(String[] arr) {
        ArrayList<String> list = new ArrayList<>();
        if (arr == null) return list;
        for (int i = 0; i < arr.length; i++) {
            list.add(arr[i]);
        }
        return list;
    }
}
